from langchain_community.chat_models import ChatTongyi
from langchain.agents import create_tool_calling_agent, AgentExecutor

from Promot import PromptClass
from Memory import MemoryClass
from Emotion import EmotionClass
from Tools import *
from MysqlTool import MysqlTool
import asyncio

msgkey=""

class AgentClass:
    def __init__(self):
        self.model_name = "qwen-turbo"
        self.chat_model = ChatTongyi(model=self.model_name)
        self.tools = [serp_search, get_info_from_local, jiemeng, MysqlTool.query_employee]
        self.memory_key = "chat_history"
        self.feeling = "default"
        self.prompt = PromptClass(memory_key=self.memory_key, feeling=self.feeling).prompt_structure()
        self.memory = MemoryClass(memory_key=self.memory_key, model=self.model_name).set_memory()
        self.emotion = EmotionClass(model=self.model_name)
        self.agent = create_tool_calling_agent(
            self.chat_model,
            self.tools,
            self.prompt,
        )
        self.agent_chain = AgentExecutor(
            agent=self.agent,
            tools=self.tools,
            memory=self.memory,
            verbose=True
        )
    def run_agent(self, input):
        # run emotion sensing
        # self.feeling = self.emotion.emotion_sensing(input)
        self.feeling = self.emotion.emotion_chain(input)
        self.prompt = PromptClass(memory_key=self.memory_key, feeling=self.feeling).prompt_structure()
        print(self.feeling)
        print(self.prompt)
        res = self.agent_chain.invoke({
            "input": input,
        })
        return res

    async def run_agent_ws(self, input):
        # run emotion sensing
        self.feeling = self.emotion.emotion_sensing(input)
        self.prompt = PromptClass(memory_key=self.memory_key, feeling=self.feeling).prompt_structure()
        async for event in self.agent_chain.astream_events({"input": input, "chat_history": self.memory}, version="v2"):
            kind = event["event"]
            if kind == "on_chat_model_stream":
                content = event["data"]["chunk"].content
                if content:
                    print(content, end="|")
                    yield content

    async def get_voice(self, text:str, uid:str):
        print("text2voice", text)
        print("uid", uid)
        # 使用百度TTS
        pass

    def background_voice_synthesis(self, text:str, uid:str):
        # 这个函数不需要返回值，只是触发了语音合成
        asyncio.run(self.get_voice(text, uid))